package org.vaadin.golfscoretracker.ui.controller;

import java.util.List;

import org.vaadin.appfoundation.persistence.facade.FacadeFactory;
import org.vaadin.golfscoretracker.data.Player;

import com.vaadin.data.Container;
import com.vaadin.data.Item;
import com.vaadin.data.util.IndexedContainer;

public class PlayerController implements DataEditorController<Player> {

    private void setProperties(Item item, Player player) {
        if (player == null) {
            throw new IllegalArgumentException("Player may not be null");
        }

        if (item == null) {
            throw new IllegalArgumentException("Item may not be null");
        }

        item.getItemProperty("name").setValue(player.getName());
    }

    @Override
    public boolean addItem(Container container, Player pojo) {
        if (pojo == null) {
            return false;
        }

        Item item = container.addItem(pojo);

        if (item == null) {
            return false;
        }

        setProperties(item, pojo);

        return true;
    }

    @Override
    public Player createPojo() {
        return new Player();
    }

    @Override
    public Container getContainer() {
        IndexedContainer container = new IndexedContainer();
        container.addContainerProperty("name", String.class, null);

        List<Player> players = FacadeFactory.getFacade().list(Player.class);
        if (players != null) {
            for (Player player : players) {
                addItem(container, player);
            }
        }

        return container;

    }

    @Override
    public void remove(Player player) {
        if (player == null) {
            throw new IllegalArgumentException("Player may not be null");
        }

        if (player.getId() == null) {
            return;
        }

        FacadeFactory.getFacade().delete(player);
    }

    @Override
    public void save(Player pojo) {
        if (pojo == null) {
            throw new IllegalArgumentException("Player may not be null");
        }

        FacadeFactory.getFacade().store(pojo);
    }

    @Override
    public void updateItemProperties(Container container, Player pojo) {
        if (pojo == null) {
            throw new IllegalArgumentException("Player may not be null");
        }

        if (container == null) {
            throw new IllegalArgumentException("Container may not be null");
        }

        Item item = container.getItem(pojo);
        setProperties(item, pojo);

    }

}
